<?php

/**
 * @author chenshubo
 * 重庆双击科技
 * 商品支持单个下单
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\VendorClient\ShopcqsjApi\ShopcqsjApiClient;
use App\Service\TaskServer\TaskWorker;
use App\Service\OrderService\BaseSupplierRouterService;

class Shopcqsj extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //下单商品重组
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $userGoodsList      = $supplierGoodsInfo['userGoodsList'];
        $goodsList          = $supplierGoodsInfo['goodsList'];
        $orderItems         = [];

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;

        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;

        //按照商品组进行拆解
        foreach ($userGoodsList as $eval )
        {
            foreach ($eval as $orderGoods )
            {
                //下单购买数量
                $goodsNum = $orderGoods['goodsNum'];
                if( $isDelare && !$isShop && $goodsNum > 1 )
                {
                    return Normal::returnCode(Normal::FAIL,"当前商品不支持多个多件套装购买[100010]");
                }

                //云仓商城进行拆分下单
                for( $i = 0 ; $i < $goodsNum ; $i++ )
                {
                    //生成供应商主单号
                    $supplierCode = $param['supplierGoodsInfo']['supplierCode'];
                    $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
                    $param['order']['supplier_csn'] = IdService::instance()->getOtherID();

                    //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
                    if( $isDelare && !$isShop ) {
                        $param['order']['supplier_dsn'] = $param['order']['orderSn'];
                    } else {
                        $param['order']['supplier_dsn'] = (string)IdService::instance()->getOtherID();
                    }

                    //将下单数量重置为1
                    $orderGoods['goodsNum']  = 1;
                    $param['order']['goods'] = [$orderGoods];
                    $param['order']['isQueryExpress'] = 1;
                    $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
                    if( $res['code'] != Normal::SUC ) {
                        return $res;
                    }
                    $orderItems[] = $res['data'];
                }
            }
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }

    /**
     * 订单支付
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        $res = $this->callSdkApi(ShopcqsjApiClient::class,$param['apiBody'])->createOrder($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $parameter = [
            [
                'tag'       => 'shopcqsj_order_push',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $res['data']['url'],
                'data'      => $res['data']['data'],
                'method'    => 'post',
                'format'    => $res['data']['format'],
                'header'    => [],
            ],
        ];

        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $result  = @json_decode($resTask['response']['result'],true);

        if( isset($result['code']) && $result['code'] == '0000' ) {
            return Normal::returnCode(Normal::SUC,$result['msg']??'推送成功');
        }

        $message = isset($result['msg']) ? $result['msg'] : '推送失败';
        return Normal::returnCode(Normal::FAIL,$message,$result['data']??[]);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function orderExpress( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }


    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }

        $supplierExpress = $this->callSdkApi(ShopcqsjApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if( $supplierExpress['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$supplierExpress['msg']);
        }

        if( empty($supplierExpress['data'])) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }

        $ships = current($supplierExpress['data']);
        if( empty($ships['shipping_name']) || empty($ships['waybill_number']) ) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }

        return  Normal::returnCode(Normal::SUC,"已发货",[
            'expressInfo' => [
                'express_name'  => mb_strtoupper($ships['shipping_name'],'utf-8'),
                'express_sn'    => $ships['waybill_number'],
            ]
        ]);
    }
}
